<template>
  <view class="bg-[#f5f5f5] min-h-screen">
    <!-- 当没有数据时显示空状态 -->
    <up-empty
      v-if="!productDetail || !productDetail.id"
      mode="data"
      text="暂无商品数据"
      margin-top="200"
    >
    </up-empty>

    <!-- 有数据时显示商品详情 -->
    <template v-else>
      <view class="relative">
        <!-- 返回按钮 -->
        <view
          class="absolute left-[20rpx] top-[20rpx] z-10"
          @click="navigateBack"
        >
          <img
            src="/static/goods/back.png"
            alt=""
            class="w-[64rpx] h-[64rpx]"
          />
        </view>
        <!-- 分享按钮 -->
        <view class="absolute right-[20rpx] top-[20rpx] z-10" @click="copyLink">
          <img
            src="/static/goods/share.png"
            alt=""
            class="w-[64rpx] h-[64rpx]"
          />
        </view>
      </view>

      <!-- 图片视频展示区域 -->
      <view class="relative">
        <!-- 轮播图 -->
        <swiper
          class="h-[838rpx] w-full"
          :indicator-dots="true"
          :autoplay="false"
          :circular="true"
          @change="handleSwiperChange"
        >
          <!-- 图片轮播 -->
          <swiper-item v-for="(item, index) in productImages" :key="index">
            <image
              :src="item.url"
              mode="aspectFill"
              class="w-full h-full"
              @click="previewImage(index)"
            />
          </swiper-item>
        </swiper>

        <!-- 轮播指示器 -->
        <view
          class="absolute bottom-[20rpx] right-[20rpx] bg-black bg-opacity-50 rounded-[30rpx] px-[20rpx] py-[6rpx] text-white"
        >
          <text>{{ currentSwiperIndex + 1 }}/{{ productImages.length }}</text>
        </view>

        <!-- 限时抢购 -->
        <view
          class="bgc pt-[6rpx] pl-[24rpx] pr-[40rpx] h-[360rpx] rounded-[32rpx] rounded-b-none"
        >
          <view class="flex items-center justify-between h-[128rpx]">
            <view class="flex flex-col">
              <span class="text-[#fff] text-[28rpx] line-through">
                原价 {{ productDetail.originalPrice }}</span
              >
              <span class="text-[#fff] text-[64rpx]">
                ￥<span class="text-3xl">{{ productDetail.price }}</span
                >.00</span
              >
            </view>
            <image
              v-if="remainingTime > 0"
              src="@/static/goods/realRushBuy.png"
              mode="scaleToFill"
              class="w-[166rpx] h-[128rpx] ml-[123rpx] mr-[40rpx]"
            />
            <view v-if="remainingTime > 0" class="flex flex-col">
              <span class="text-[#D7A56B] text-[28rpx]">剩余时间</span>
              <span class="text-[#D7A56B] text-[28rpx]">{{
                handleTime(remainingTime)
              }}</span>
            </view>
          </view>
          <view class="bg-[#fff] h-[165rpx] rounded-[16rpx] p-[24rpx]">
            <span class="text-[34rpx] color-[#323233]">{{
              productDetail.description
            }}</span>
          </view>
        </view>
      </view>

      <!-- 产品详情 -->
      <view
        class="goodsDetail bg-white p-[30rpx] mb-[20rpx] ml-[24rpx] mr-[24rpx] rounded-[16rpx] z-10"
      >
        <view class="color-[#000000] text-[34rpx] pl-[20rpx] mb-[44rpx]"
          >产品详情</view
        >

        <!-- 产品详情内容 -->
        <view v-if="productDetail.detail" class="product-detail-content">
          <rich-text :nodes="productDetail.detail"></rich-text>
        </view>

        <!-- 默认内容（当没有detail字段时显示） -->
        <template v-else>
          <u-empty mode="data" text="暂无详情"></u-empty>
        </template>
      </view>

      <!-- 底部购买栏 -->
      <view
        class="fixed h-[108rpx] left-0 right-0 bottom-0 bg-white flex items-center pl-[24rpx] pr-[24rpx] border-t border-[#eee]"
        style="z-index: 999"
      >
        <view
          class="flex items-center"
          v-if="productDetail.isIntegralProduct === 0"
          @click="handleIntegralBuy"
        >
          <view class="flex flex-col items-center mr-[40rpx]">
            <img
              src="@/static/goods/pointsRedemption.png"
              alt=""
              class="w-[42rpx] h-[38rpx]"
            />
            <text class="text-[24rpx] text-[#666]">积分兑换</text>
          </view>
        </view>
        <view
          class="btn-color text-white h-[88rpx] rounded-[40rpx] text-[32rpx] flex flex-1 items-center justify-center"
          @click="handleBuy"
        >
          {{ productDetail.isProduct === 0 ? "立即购买" : "立即预约" }}
        </view>
      </view>
    </template>
  </view>
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from "vue";
import { getProductDetail, createOrder } from "@/api/home";
import { upload_url } from "@/utils/config";
import type { HotProjectResponseData } from "@/api/home";
import { onLoad, onShow, onUnload } from "@dcloudio/uni-app";
import { getUserInfo } from "@/api"; // 添加用户API导入
const id = ref(0);

const productDetail = ref<HotProjectResponseData>({} as HotProjectResponseData);
const isLoading = ref(true);
const remainingTime = ref(0);
let timer: number | null = null;

// 媒体数据（视频+图片）
const productMedias = ref<
  Array<{ url: string; type: "video" | "image"; poster?: string }>
>([]);
// 仅图片数据（用于预览）
const productImages = ref<Array<{ url: string }>>([]);
// 当前轮播索引
const currentSwiperIndex = ref(0);
// 详情图片数组
const detailImageUrls = ref<string[]>([]);

onLoad((options) => {
  if (options?.id) {
    id.value = Number(options.id);
  }
});

// 监听轮播索引变化
watch(currentSwiperIndex, (newIndex, oldIndex) => {
  // 轮播图切换时的逻辑（如果需要的话）
});

onMounted(() => {
  // 组件挂载时的初始化逻辑
});

const userId = ref(0);
const paymentType = ref(0);

onShow(() => {
  handleGetProductDetail();
  userId.value = uni.getStorageSync("userInfo").id;
});

// 页面卸载时清除定时器
onUnload(() => {
  if (timer) {
    clearInterval(timer);
    timer = null;
  }
});

// 轮播图切换事件
function handleSwiperChange(e: any) {
  const newIndex = e.detail.current;
  currentSwiperIndex.value = newIndex;
}

// 复制链接功能
function copyLink() {
  // #ifdef H5
  try {
    const currentUrl = window.location.href;
    // 创建临时输入框
    const input = document.createElement("input");
    document.body.appendChild(input);
    input.setAttribute("value", currentUrl);
    input.select();
    // 执行复制命令
    document.execCommand("copy");
    document.body.removeChild(input);

    uni.showToast({
      title: "链接已复制，可粘贴给好友",
      icon: "none",
      duration: 2000,
    });
  } catch (error) {
    console.error("复制链接失败:", error);
    uni.showToast({
      title: "复制失败",
      icon: "none",
    });
  }
  // #endif
}

function navigateBack() {
  uni.navigateBack();
}

async function handleBuy() {
  if (productDetail.value.isProduct === 0) {
    paymentType.value = 0;
    await handleCreateOrder();
  } else {
    // 项目
    uni.navigateTo({
      url:
        "/pages/home/goodsReservation?id=" +
        productDetail.value.id +
        "&isProduct=" +
        productDetail.value.isProduct +
        "&price=" +
        productDetail.value.price +
        "&paymentType=" +
        0,
    });
  }
}

// 预览图片
function previewImage(index: number) {
  // 只传递图片URL数组给预览组件
  const imageUrls = productImages.value.map((item) => item.url);
  uni.previewImage({
    urls: imageUrls,
    current: imageUrls[index],
    indicator: "number",
    loop: true,
  });
}

// 积分兑换
function handleIntegralBuy() {
  if (productDetail.value.isIntegralProduct === 1) {
    uni.showToast({
      title: "该商品不支持积分兑换",
      icon: "none",
    });
    return;
  }

  // 获取用户积分信息
  getUserInfo(userId.value.toString())
    .then((res: any) => {
      if (res.code === 200) {
        const userIntegral = res.data.integral || 0;
        const requiredIntegral = productDetail.value.integralPrice || 0;

        uni.showModal({
          title: "积分兑换",
          content: `该商品需要${requiredIntegral}积分，您当前剩余${userIntegral}积分`,
          confirmText: "确认兑换",
          cancelText: "取消",
          success: function (res) {
            if (res.confirm) {
              // 用户点击确认，执行兑换逻辑
              if (userIntegral >= requiredIntegral) {
                // 执行积分兑换API
                exchangeProduct(
                  productDetail.value.id,
                  Number(productDetail.value.isProduct),
                  1,
                );
              } else {
                uni.showToast({
                  title: "积分不足",
                  icon: "none",
                });
              }
            }
          },
        });
      } else {
        uni.showToast({
          title: "获取用户信息失败",
          icon: "none",
        });
      }
    })
    .catch(() => {
      uni.showToast({
        title: "获取用户信息失败",
        icon: "none",
      });
    });
}

/**
 * 兑换商品
 * @param productId 商品id
 * @param isProduct 是否是产品 0产品 1项目
 * @param paymentType 支付类型 0现金 1积分
 */
async function exchangeProduct(
  productId: number,
  isProduct: number,
  paymentType: number,
) {
  // 如果是项目 跳转到预约页面
  if (isProduct === 1) {
    uni.navigateTo({
      url:
        "/pages/home/goodsReservation?id=" +
        productId +
        "&isProduct=" +
        isProduct +
        "&price=" +
        productDetail.value.price +
        "&paymentType=" +
        paymentType,
    });
    return;
  } else {
    // 如果是产品 跳转到购买页面
    paymentType.value = 0;
    await handleCreateOrder();
  }
}

// 创建订单
async function handleCreateOrder() {
  let res = await createOrder({
    userId: userId.value,
    projectId: productDetail.value.id,
    paymentType: paymentType.value, // 0-现金支付，1-积分支付
    doctorId: 0,
    totalPrice: productDetail.value.price,
    remainingSessions: 0,
    appointmentDate: "",
    appointmentTime: "",
    isMorning: null,
  });
  if (res.code === 200) {
    uni.showToast({
      title: "创建订单成功",
      icon: "none",
    });
    uni.navigateTo({
      url: "/pages/home/successfully?id=" + res.data.masterId + "&isProduct=0",
    });
  }
}

const handleGetProductDetail = () => {
  isLoading.value = true;
  getProductDetail(id.value)
    .then((res) => {
      isLoading.value = false;
      if (res.code === 200) {
        productDetail.value = res.data;

        // 打印detail字段用于调试
        console.log("产品详情内容:", res.data.detail);

        // 初始化倒计时
        remainingTime.value = res.data.remainingPromotionTime;
        // 启动倒计时
        startCountdown();

        // 初始化媒体数据
        initMediaData();
      }
      console.log(res);
    })
    .catch(() => {
      isLoading.value = false;
    });
};

// 初始化媒体数据
const initMediaData = () => {
  // 这里使用可选链，避免TypeScript错误
  // 由于接口类型中没有medias字段，使用as any来避免类型错误
  const medias = (productDetail.value as any)?.medias || [];

  if (medias.length > 0) {
    productMedias.value = medias;
  } else {
    // 分割 detailImgUrl 中的逗号分隔字符串
    const detailImages = productDetail.value.detailImgUrl
      ? productDetail.value.detailImgUrl.split(",").filter((url) => url.trim())
      : [];

    // 存储详情图片数组
    detailImageUrls.value = detailImages.map((url) => upload_url + url.trim());
    console.log(detailImageUrls.value);

    // 构建媒体数据：只使用分割后的详情图片，不包含视频
    productMedias.value = detailImages.map((url) => ({
      url: upload_url + url.trim(),
      type: "image" as const,
    }));
  }

  // 提取所有图片用于预览
  productImages.value = productMedias.value
    .filter((item) => item.type === "image")
    .map((item) => ({ url: item.url }));
};

/**
 * 启动倒计时
 */
const startCountdown = () => {
  // 清除可能存在的旧定时器
  if (timer) {
    clearInterval(timer);
  }

  // 创建新的定时器，每秒减一
  timer = setInterval(() => {
    if (remainingTime.value > 0) {
      remainingTime.value--;
    } else {
      // 时间到，清除定时器
      if (timer) {
        clearInterval(timer);
        timer = null;
      }
    }
  }, 1000);
};

/**
 *用秒 改成00:00:00
 * @param time 秒
 */
const handleTime = (time: number) => {
  const hours = Math.floor(time / 3600);
  const minutes = Math.floor((time % 3600) / 60);
  const seconds = time % 60;
  return `${hours.toString().padStart(2, "0")}:${minutes
    .toString()
    .padStart(2, "0")}:${seconds.toString().padStart(2, "0")}`;
};
</script>

<style lang="scss" scoped>
.bgc {
  box-sizing: border-box;
  background: linear-gradient(274deg, #fff5e0 0%, #deb279 100%);
  border-radius: 32rpx 32rpx 0rpx 0rpx;
  position: absolute;
  bottom: -232rpx;
  left: 0;
  right: 0;
  z-index: 1;
}

.goodsDetail {
  padding-bottom: 118rpx;
  position: absolute;
  top: calc(838rpx + 165rpx + 20rpx);
  left: 0;
  right: 0;
}
.btn-color {
  background: linear-gradient(270deg, #d7a56b 0%, #ebd7ac 100%, #a58c56 100%);
  border-radius: 44rpx;
}
</style>
